<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.merchandiseSn" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Merchandise_number')" />
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Product_name')" />
      <el-input v-model="listQuery.categoryName" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('Product_category')" />
      <el-button class="filter-item" type="primary" icon="el-icon-search"
        @click="handleFilter">{{ $t('Search') }}</el-button>
      <el-button v-permission="['GET /admin/p/stock_productapply_apply']" v-shop="true" class="filter-item"
        type="primary" icon="el-icon-edit" @click="handleGetAllmerchandise">{{ $t('Restock_request') }}</el-button>
      <el-button v-permission="['GET /admin/p/stock_product_sync']" class="filter-item" type="primary"
        icon="el-icon-refresh" @click="handleSyncErp">{{ $t('Sync') }}</el-button>
    </div>


    <!-- 查询结果 -->
    <el-table ref="table" v-loading="listLoading" :data="list" @select="handleSelectRow" @select-all="handleSelectAll"
      :element-loading-text="$t('Searching')" border fit highlight-current-row>
      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" :index="getIndex" width="50"></el-table-column>

      <el-table-column align="center" min-width="100" :label="$t('Merchandise_number')" prop="barCode" />

      <el-table-column align="center" min-width="100" :label="$t('Product_name')" prop="name" />

      <el-table-column align="center" min-width="100" :label="$t('Merchandise_picture')" prop="picUrl">
        <template slot-scope="scope">
          <img :src="scope.row.picUrl" width="40">
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Specifications')" prop="standard" />

      <el-table-column align="center" :label="$t('Model')" prop="model" />

      <el-table-column align="center" :label="$t('Product_category')" prop="categoryName" />

      <el-table-column align="center" :label="$t('Product_unit')" prop="unitName" />
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { materialList, materialApply, billnumber } from '@/api/erp'
import { MessageBox, Loading } from 'element-ui'
import { syncErp } from '@/api/erp'


export default {
  name: 'Merchandise',
  components: { Pagination },
  data() {
    return {
      total: 0,
      listLoading: false,
      downloadLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        merchandiseSn: undefined,
        name: undefined,
        categoryName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      list: [],
      selectedData: []
    }
  },
  created() {
    if (this.$route.query.shopId) {
      this.listQuery.shopId = this.$route.query.shopId
    }
    this.getList()
  },
  methods: {
    handleSyncErp() {
      let loadingInstance = Loading.service({
        text: this.$t('Syncing')
      });
      syncErp().then(response => {
        this.getList()

        this.$nextTick(() => {
          loadingInstance.close();
        });

        this.$notify.success({
          title: this.$t('Success!'),
          message: '操作成功'
        })
      })
        .catch(response => {
          this.$nextTick(() => {
            loadingInstance.close();
          });
          MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
            confirmButtonText: this.$t('Confirm'),
            type: 'error'
          })
        })
    },
    getList() {
      materialList(this.listQuery).then(res => {
        this.list = res.data.data.rows
        this.total = res.data.data.total

        this.$nextTick(() => {
          this.memoryChecked()
        })
      }).catch(() => {
        this.list = []
        this.listLoading = false
      })
    },
    handleFilter() {
      this.getList()
    },
    //行选中函数  若有删除，若无添加
    handleSelectRow(selection, row) {
      if (this.selectedData[row.id]) {
        delete this.selectedData[row.id]
      } else {
        this.selectedData[row.id] = row
      }
    },
    //全选函数  点击全选遍历当页数据若无添加,若是反选则删除(判断是否是全选还是反选)
    handleSelectAll(selection) {
      this.list.forEach((row, index) => {
        if (this.selectedData.hasOwnProperty(row.id)) {
          selection.length ? null : delete this.selectedData[row.id]
        } else {
          this.selectedData[row.id] = row
        }
      });
    },
    //记忆函数
    memoryChecked() {
      this.list.forEach((row, index) => {
        if (this.selectedData.hasOwnProperty(row.id)) {
          this.$refs['table'].toggleRowSelection(row, true);
        } else {
          this.$refs['table'].toggleRowSelection(row, false);
        }
      });
    },
    handleGetAllmerchandise() {
      const merchandises = [];
      for (var id in this.selectedData) {
        merchandises.push(this.selectedData[id])
      }
      if (merchandises.length == 0) {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t('请选择数据')
        })
      } else {
        this.$router.push({ path: '/repository/apply', query: { merchandises: merchandises } })
      }
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    }
  }
}
</script>

<style scoped>

</style>
